package com.punai.customer.controller;

import cn.hutool.core.util.StrUtil;
import com.punai.common.annotation.Log;
import com.punai.common.core.controller.BaseController;
import com.punai.common.core.domain.AjaxResult;
import com.punai.common.core.page.TableDataInfo;
import com.punai.common.enums.BusinessType;
import com.punai.common.utils.file.FileUtils;
import com.punai.customer.domain.CusMechanicalItem;
import com.punai.customer.domain.CusVersionsDiscrepancy;
import com.punai.customer.domain.contants.CusConstants;
import com.punai.customer.domain.request.CusMechanicalItemRequest;
import com.punai.customer.domain.request.CusRewriteCodeRequest;
import com.punai.customer.service.ICusMechanicalItemService;
import com.punai.customer.service.ICusVersionsDiscrepancyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 机械费用项Controller
 * 
 * @author ruoyi
 * @date 2022-12-04
 */
@RestController
@RequestMapping("/cus/mechanicalItem")
public class CusMechanicalItemController extends BaseController
{

    private static final Logger log = LoggerFactory.getLogger(CusMechanicalItemController.class);

    @Autowired
    private ICusMechanicalItemService cusMechanicalItemService;
    @Autowired
    private ICusVersionsDiscrepancyService cusVersionsDiscrepancyService;

    /**
     * 查询机械费用项列表
     */
    @PreAuthorize("@ss.hasPermi('cus:mechanicalItem:list')")
    @GetMapping("/list")
    public TableDataInfo list(CusMechanicalItem cusMechanicalItem)
    {
        if (StrUtil.isEmpty(cusMechanicalItem.getChapterId())) {
            getDataTable(new ArrayList<>());
        }
        startPage();
        cusMechanicalItem.setCompanyId(getCompanyId());
        return getDataTable(cusMechanicalItemService.selectCusMechanicalItemList(cusMechanicalItem));
    }

    /**
     * 获取机械费用项详细信息
     */
    @PreAuthorize("@ss.hasPermi('cus:mechanicalItem:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(cusMechanicalItemService.selectCusMechanicalItemById(id,getCompanyId()));
    }

    /**
     * 新增机械费用项
     */
    @PreAuthorize("@ss.hasPermi('cus:mechanicalItem:add')")
    @Log(title = CusConstants.JX_NAME, businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CusMechanicalItemRequest cusMechanicalItemRequest)
    {
        return toAjax(cusMechanicalItemService.insertCusMechanicalItem(cusMechanicalItemRequest));
    }

    /**
     * 修改机械费用项
     */
    @PreAuthorize("@ss.hasPermi('cus:mechanicalItem:edit')")
    @Log(title = CusConstants.JX_NAME, businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CusMechanicalItemRequest cusMechanicalItemRequest)
    {
        return toAjax(cusMechanicalItemService.updateCusMechanicalItem(cusMechanicalItemRequest));
    }

    @PreAuthorize("@ss.hasPermi('cus:mechanicalItem:edit')")
    @Log(title = CusConstants.JX_NAME + "-重新编码", businessType = BusinessType.UPDATE)
    @PostMapping("/rewriteCode")
    public AjaxResult rewriteCode(@RequestBody CusRewriteCodeRequest codeRequest)
    {
        return toAjax(cusMechanicalItemService.rewriteCode(codeRequest));
    }

    /**
     * 删除机械费用项
     */
    @PreAuthorize("@ss.hasPermi('cus:mechanicalItem:remove')")
    @Log(title = CusConstants.JX_NAME, businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids)
    {
        return toAjax(cusMechanicalItemService.deleteCusMechanicalItemByIds(ids,getCompanyId()));
    }

    @PreAuthorize("@ss.hasPermi('cus:mechanicalItem:edit')")
    @Log(title = CusConstants.JX_NAME + "-修改功耗值", businessType = BusinessType.UPDATE)
    @PutMapping("/setConsumptionVal/{id}/{consumption}")
    public AjaxResult setConsumptionVal(@PathVariable String id, @PathVariable BigDecimal consumption) {

        return toAjax(cusMechanicalItemService.setConsumptionVal(id, consumption,getCompanyId()));
    }

    @PreAuthorize("@ss.hasPermi('cus:mechanicalItem:editChapter')")
    @Log(title = CusConstants.JX_NAME + "-移动费用项", businessType = BusinessType.UPDATE)
    @PutMapping("/moveToChapter/{ids}/{chapterId}")
    public AjaxResult moveToChapter(@PathVariable String[] ids,@PathVariable String chapterId)
    {
        return toAjax(cusMechanicalItemService.moveToChapter(ids,chapterId,getCompanyId()));
    }

    @GetMapping(value = "/countChapterIdIsZero")
    public AjaxResult countChapterIdIsZero()
    {
        return AjaxResult.success(cusMechanicalItemService.countChapterIdIsZero(getCompanyId()));
    }


    @Log(title = CusConstants.JX_NAME + "-下载模板", businessType = BusinessType.UPDATE)
    @PostMapping("/downloadMechanicalExcelTemplate")
    public void downloadMaterialExcelTemplate(HttpServletResponse response)
    {
        try
        {
            String mechanicalExcelName = CusConstants.MechanicalExcelName;
            Resource resource = new ClassPathResource("template/"+mechanicalExcelName);
            //放弃使用直接获取文件的方式, 改成使用流的方式
            BufferedInputStream bis = new BufferedInputStream(resource.getInputStream());
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, "机械导入模板.xlsx");
            FileUtils.downloadFile(bis, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    @GetMapping("/getContrastData")
    public TableDataInfo getDataLog(CusVersionsDiscrepancy cusVersionsDiscrepancy) {
        startPage();
        cusVersionsDiscrepancy.setCompanyId(getCompanyId());
        cusVersionsDiscrepancy.setPublishType(CusConstants.JX_TYPE);
        return getDataTable(cusVersionsDiscrepancyService.selectStaVersionsDiscrepancyList(cusVersionsDiscrepancy));
    }

    @GetMapping( "/validateCode")
    public AjaxResult validateCode()
    {
        return AjaxResult.success(cusMechanicalItemService.validateCode(getCompanyId()));
    }


}
